package com.haoxuer.discover.article.data.dao.impl;

import com.haoxuer.discover.article.data.dao.ArticleCatalogDao;
import com.haoxuer.discover.data.core.Finder;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.haoxuer.discover.article.data.entity.ArticleCatalog;
import com.haoxuer.discover.data.core.CatalogDaoImpl;

import java.util.Date;

/**
 * Created by imake on 2017年08月15日09:52:12.
 */
@Repository

public class ArticleCatalogDaoImpl extends CatalogDaoImpl<ArticleCatalog, Integer> implements ArticleCatalogDao {

    @Override
    public ArticleCatalog findById(Integer id) {
        if (id == null) {
            return null;
        }
        return get(id);
    }

    @Override
    public ArticleCatalog save(ArticleCatalog bean) {

        add(bean);


        return bean;
    }

    @Override
    public ArticleCatalog deleteById(Integer id) {
        ArticleCatalog entity = super.get(id);
        if (entity != null) {
            getSession().delete(entity);
        }
        return entity;
    }

    @Override
    protected Class<ArticleCatalog> getEntityClass() {
        return ArticleCatalog.class;
    }

    @Autowired
    public void setSuperSessionFactory(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }


    @Override
    public Integer updateNums(Integer id) {

        Integer result = 0;
        ArticleCatalog cur = findById(id);
        if (cur == null) {
            return result;
        }
        do {
            counts(cur);
            cur = cur.getParent();
            result++;
        } while (cur != null);

        return result;
    }

    private void counts(ArticleCatalog cur) {
        Finder finder = Finder.create();
        finder.append("from Article a where a.catalog.lft >= :lft ");
        finder.setParam("lft", cur.getLft());
        finder.append(" and a.catalog.rgt <= :rgt");
        finder.setParam("rgt", cur.getRgt());
        Long size = countQuery(finder);
        cur.setAmount(size);
        cur.setLastDate(new Date());
    }
}